package com.fly.locks.thread.adder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;

import org.springframework.util.StopWatch;

import lombok.extern.slf4j.Slf4j;

/**
 * @description 压测LongAdder的原子操作性能
 **/
@Slf4j
public class LongAdderRunnable implements Runnable
{
    private static LongAdder longAdder = new LongAdder();
    
    @Override
    public void run()
    {
        for (int i = 0; i < 10000; i++)
        {
            longAdder.increment();
        }
    }
    
    public static void main(String[] args)
    {
        ExecutorService es = Executors.newFixedThreadPool(30);
        Runnable runnable = new LongAdderRunnable();
        StopWatch clock = new StopWatch();
        clock.start();
        for (int i = 0; i < 10000; i++)
        {
            es.submit(runnable);
        }
        es.shutdown();
        // 保证任务全部执行完
        while (!es.isTerminated())
        {
        }
        clock.stop();
        log.info("业务处理完毕,计数器自减：{}", longAdder.sum());
        log.info("运行 {} ms ---------------", clock.getLastTaskTimeMillis());
    }
}